package dao

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"web_api_gin/dto"
	"web_api_gin/entity"
)

var SysMenuGroup = SysMenuGroupDao{}

type SysMenuGroupDao struct {
}

// 获取分组列表
func (d *SysMenuGroupDao) GetMenuGroupList(ctx *gin.Context, searchParams *dto.SysMenuGroupGetListRequest) ([]*entity.SysMenuGroup, int64, error) {
	var total int64
	var list []*entity.SysMenuGroup
	tx := DB(ctx).Model(&entity.SysMenuGroup{})
	if searchParams.GroupName != "" {
		tx = tx.Where("group_name like ?", "%"+searchParams.GroupName+"%")
	}
	if searchParams.GroupKey != "" {
		tx = tx.Where("group_key like ?", "%"+searchParams.GroupKey+"%")
	}
	rs := tx.Count(&total).Order("group_id ASC").Find(&list)
	return list, total, rs.Error
}

// 通过分组key获取分组信息
func (d *SysMenuGroupDao) GetGroupDataByKey(ctx *gin.Context, groupKey string) (*entity.SysMenuGroup, error) {
	var menuGroup *entity.SysMenuGroup
	result := DB(ctx).Where(&entity.SysMenuGroup{GroupKey: groupKey}).First(&menuGroup)
	return menuGroup, result.Error
}

//保存分组数据
func (d *SysMenuGroupDao) SaveMenuGroup(ctx *gin.Context, data *entity.SysMenuGroup) (int64, error) {
	var rs *gorm.DB
	if data.GroupId != 0 {
		rs = DB(ctx).Where("group_id = ?", data.GroupId).Updates(data)
	} else {
		rs = DB(ctx).Create(data)
	}
	return rs.RowsAffected, rs.Error
}

//删除分组
func (d *SysMenuGroupDao) DelMenuGroup(ctx *gin.Context, groupIds []uint32) (int64, error) {
	rs := DB(ctx).Unscoped().Delete(&entity.SysMenuGroup{}, groupIds)
	return rs.RowsAffected, rs.Error
}
